package com.it.filter;

import com.it.utils.TransactionManager;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter("*.do")
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
         //
        try {
            TransactionManager.beginTransaction();
            filterChain.doFilter(servletRequest, servletResponse);
            TransactionManager.commitTransaction();
        } catch (Exception e) {
            try {
                System.out.println("全局获取异常 = "+e);
                e.printStackTrace();
                TransactionManager.rollBackTransaction();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

    @Override
    public void destroy() {
        System.out.println("MyFilter destroy");
    }
}
